package com.sd.activity;
import java.io.IOException;
import java.util.Vector;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EncodingUtils;

import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.alex.log.ALog;
import com.mobclick.android.MobclickAgent;
import com.sd.activity.r.R;
import com.sd.database.BetaReadDao;
import com.sd.database.ScanItem;
import com.sd.util.HttpUtil;
import com.sd.util.LoadingProgressDialog;
import com.sd.util.PreferencesManager;
import com.sd.util.StringUtils;
import com.sd.util.WebUtil;
import com.sd.view.DialogManager;
import com.sd.view.ToastManager;
import com.sd.view.WapMenuAdapter;
import com.snda.woa.android.OpenAPI;
import com.snda.woa.android.callback.FastLoginCallBack;
import com.snda.woa.android.callback.PwdLoginCallBack;

/**
 * 
 * WAP界面
 * 
 * @author Alex.Lu
 * 
 */
public class BookStoreActivity extends BaseActivity implements OnClickListener,
		OnCancelListener, OnChildClickListener, OnGroupClickListener,
		PwdLoginCallBack, OnTouchListener {

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if(slidingDrawer.isOpened()){
			slidingDrawer.close();
		}
		super.onPause();
	}

	public static String user = "";
	private static WebView mWebView;
	private WebSettings mWebSettings;
	private ImageButton mRechangeBT;
	private ImageButton mUserBT;
	private LayoutInflater mInflater;
	private ExpandableListView mWapMenu;
	private SlidingDrawer slidingDrawer;
	private ProgressBar bar;
	private RelativeLayout onNoWebView;
	private ImageView mScreenBT;
	private RelativeLayout mTitleRL;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_bookstore);
		mInflater = LayoutInflater.from(this);
		mRechangeBT = (ImageButton) findViewById(R.id.recharge_bt);
		mRechangeBT.setOnClickListener(this);
		mUserBT = (ImageButton) findViewById(R.id.user_bt);
		mUserBT.setOnClickListener(this);
		
		mTitleRL = (RelativeLayout)findViewById(R.id.titleRL);
		BookStoreActivity.user = PreferencesManager.getInstance().getSid();
		initWAPMenu();
		initWebView();
		mScreenBT = (ImageView)findViewById(R.id.screenBt);
		mScreenBT.setOnClickListener(this);
		OpenAPI.init(this);
		
	}

	Vector<ScanItem> scans;
	WapMenuAdapter adapter;

	
	/**
	 * 初始化menu
	 */
	private void initWAPMenu() {
		// TODO Auto-generated method stub
		slidingDrawer = (SlidingDrawer) findViewById(R.id.sliding_drawer);
		mWapMenu = (ExpandableListView) findViewById(R.id.wap_menu);
		bar = (ProgressBar)findViewById(R.id.loadweb_bar);
		mWapMenu.setGroupIndicator(this.getResources().getDrawable(
				R.drawable.ohno));
		scans = BetaReadDao.queryScanItems(this);
		adapter = new WapMenuAdapter(this, scans);
		mWapMenu.setAdapter(adapter);
		mWapMenu.setOnChildClickListener(this);
		mWapMenu.setOnGroupClickListener(this);
		final ImageButton mPanelHandle = (ImageButton) findViewById(R.id.panelHandle);
		slidingDrawer
				.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {

					public void onDrawerOpened() {
						mPanelHandle.setImageResource(R.drawable.wap_menu_bg2);
					}
				});
		slidingDrawer
				.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {

					public void onDrawerClosed() {
						mPanelHandle.setImageResource(R.drawable.wap_menu_bg);
					}
				});
	}
	WebViewClientDemo client = new WebViewClientDemo();
	/**
	 * 初始化
	 */
	private void initWebView() {
		onNoWebView = (RelativeLayout)findViewById(R.id.ohnowebiew);
		onNoWebView.setVisibility(View.VISIBLE);
		
		mWebView = (WebView) findViewById(R.id.webview);
		// CookieManager.getInstance().removeExpiredCookie();
		// 设置支持JavaScript等
		mWebSettings = mWebView.getSettings();
		mWebSettings.setJavaScriptEnabled(true);
		mWebSettings.setLightTouchEnabled(true);
		mWebSettings.setSupportZoom(false);
		mWebView.setHapticFeedbackEnabled(false);
		
		mWebView.setWebViewClient(client);
		String url = WebUtil.getSid("http://wap.qidian.cn/wap2/index.do?");
		mWebView.loadUrl(url);
		
		mWebView.setOnTouchListener(this);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(slidingDrawer.isOpened()){
			slidingDrawer.close();
		}else if (mWebView.canGoBack()) {
			mWebView.goBack();
		}else{
			 DialogManager.getInstance().createExitDialog(this);
		}
	}
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.user_bt:
			MobclickAgent.onEvent(this, "bookstore","user_bt");
			if(user !=null && user.equals("")){
				DialogManager.getInstance().createLogin(this, this, callback);
			}else{
				mWebView.loadUrl(WebUtil.getSid("http://wap.qidian.cn/wap2/user/mybookroom.do?userId=&type=2&mtd=sdoUserFavorites"));
			}
			break;
		case R.id.recharge_bt:
			MobclickAgent.onEvent(this, "bookstore","recharge_bt");
			if(user !=null && user.equals("")){
				ToastManager.getInstance().showText(this, R.string.msg_error_login_first);
			}else{
				DialogManager.getInstance().createRechange(this, this);
			}
			
			break;
		case R.id.screenBt:
			if(mTitleRL.getVisibility() == View.GONE){
				mTitleRL.setVisibility(View.VISIBLE);
				((TabActivity)this.getParent()).getTabWidget().setVisibility(View.VISIBLE);
				mScreenBT.setImageResource(R.drawable.screen_ful);
			}else{
				mTitleRL.setVisibility(View.GONE);
				((TabActivity)this.getParent()).getTabWidget().setVisibility(View.GONE);
				mScreenBT.setImageResource(R.drawable.screen_unful);
			}
			break;
		default:
			break;
		}
	}

	static String search;

	public static void search(String searchUrl) {
		//String postUrl = "http://wap.qidian.cn/wap2/pay/unihjsmschannellist.do?mtd=unihjsmschannellist&sid=6238031;;1512d168163f7e8b0dda9f3719f22130;;0";
		String postUrl = "http://search.qidian.cn:8020/wap2/book/booksearch_do.do?fromindex=ss0";
		StringBuffer postData = new StringBuffer();
		postData.append("keywords=");
		postData.append(searchUrl);
		postData.append("&type=0&mtd=bookSearch");
		mWebView.postUrl(postUrl, EncodingUtils.getBytes(postData.toString(),"BASE64"));
	}
	
	public static void goBook(String bookid) {
		if(bookid!=null){
			bookid = bookid.substring(bookid.indexOf("-")+1);
			//String postUrl = "http://wap.qidian.cn/wap2/pay/unihjsmschannellist.do?mtd=unihjsmschannellist&sid=6238031;;1512d168163f7e8b0dda9f3719f22130;;0";
			StringBuffer url = new StringBuffer();
			url.append("http://qidian.cn/yunlinkIn.jsp?id=web&bookid=");
			url.append(bookid);
			url.append("&t=2");
			mWebView.loadUrl(url.toString());
		}
	}

	

	private class WebViewClientDemo extends WebViewClient {

		
		// 在WebView中而不是默认浏览器中显示页面
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			//ALog.e("shouldOverrideUrlLoading  url:"+url + "code:" + getRespStatus(url));
			String tempUrl = url;
			ALog.e(url);
			if(url.contains("sms:")){
				Uri uri = Uri.parse(url);
				Intent it = new Intent(Intent.ACTION_SENDTO, uri);
				int start = url.indexOf("body=") + 5;
				it.putExtra("sms_body", url.substring(start));
				startActivity(it);
			} else if(url.contains("wtai:")){
				int start = url.indexOf("wtai://wp/mc;") + 13;
				Uri uri = Uri.parse("tel:"+url.substring(start));
				Intent it = new Intent(Intent.ACTION_DIAL, uri);
				startActivity(it);
			} else{
				tempUrl = WebUtil.getSid(url);
				view.loadUrl(tempUrl);
			}
			
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			onNoWebView.setVisibility(View.GONE);
			mWebView.setVisibility(View.VISIBLE);
			bar.setVisibility(View.VISIBLE);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			bar.setVisibility(View.INVISIBLE);
			ScanItem item = new ScanItem();
			item.name = view.getTitle();
			item.url = view.getUrl();
			adapter.addHistory(item);
			BetaReadDao.insertScanItem(BookStoreActivity.this, item);
			
			adapter.notifyDataSetChanged();
			super.onPageFinished(view, url);
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onLoadResource(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// TODO Auto-generated method stub
			LoadingProgressDialog.dismiss();
			mWebView.setVisibility(View.GONE);
			onNoWebView.setVisibility(View.VISIBLE);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
	}

	private int getRespStatus(String url) {
        int status = -1;
        try {
                HttpHead head = new HttpHead(url);
                HttpClient client = new DefaultHttpClient();
                HttpResponse resp = client.execute(head);
                status = resp.getStatusLine().getStatusCode();
        } catch (IOException e) {}
        return status;
}
	
	
	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		mWebView.stopLoading();
		LoadingProgressDialog.dismiss();
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		// TODO Auto-generated method stub
		WapMenuAdapter.MenuItem item = ((WapMenuAdapter.MenuItem) (parent
				.getItemAtPosition(groupPosition))).list.get(childPosition);
		String url = WebUtil.getSid(item.url);
		mWebView.loadUrl(url);
		slidingDrawer.close();
		return false;
	}

	
	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		Log.d("", "onGroupClick id:"+id+"  :"+groupPosition);
		WapMenuAdapter.MenuItem item = WapMenuAdapter.mList.get(groupPosition);
		if (item.tag != 0 ) {
			if(item.tag ==4 ){
				if(!user.equals("")){
					user = "";
					CookieManager.getInstance().removeAllCookie();
					CookieManager.getInstance().setAcceptCookie(true);
					CookieManager.getInstance().setCookie("http://wap.qidian.cn", "");
					PreferencesManager.getInstance().setSid(user);
					mWebView.loadUrl(WebUtil.getSid(mWebView.getUrl()));
				}
				DialogManager.getInstance().createLogin(this, this, callback);
			}else{
				String url = WebUtil.getSid(item.url);
				mWebView.loadUrl(url);
			}
			slidingDrawer.close();
		}
		
		return false;
	}

	/***********
	 * 账号登陆回调函数
	 */
	/****************************************************************************/
	// 登录令牌
	protected String token;
	// sessionId验证返回结果码
	protected String resultCode;

	@Override
	public void callBack(int code, String message, String sessionId) {
		// TODO Auto-generated method stub
		ALog.e("callBack:" + code);
		LoadingProgressDialog.dismiss();
		// sessionId由sdk回调返回
		if (StringUtils.checkCallBackStat(code, sessionId)) {
			// 通过应用自身服务端与woa服务端进行sessionId验证（此步骤是判断登录成功与否的关键）
			String result = HttpUtil.readStringFromUrl("20008", sessionId,
					"utf-8", new Object());
			if (result != null) {
				
				token = StringUtils.getValueByKey(result, "proxyTicket");
				resultCode = StringUtils.getValueByKey(result, "Result");
				if (!StringUtils.isEmpty(token) && "0".equals(resultCode)) {
					CookieManager.getInstance().removeAllCookie();
					BookStoreActivity.user = StringUtils.getValueByKey(result,
					"sid");
					MobclickAgent.onEvent(BookStoreActivity.this, "bookstore","user:"+BookStoreActivity.user);
					PreferencesManager.getInstance().setSid(user);
					mWebView.loadUrl(WebUtil.getSid(mWebView.getUrl()));
					// 验证完sessionId后不管成功与否，都需要反馈给sdk
					// 调用反馈接口（接口参数：应用上下文，是否登录成功，sessionId验证返回的结果码，验证获取的token）
					// sessionId验证成功即可认为是此次登录成功
					OpenAPI.loginFeedBack(this, true,
							resultCode != null ? Integer.valueOf(resultCode)
									: -1, token);
					return ;
				} else {
					// sessionId验证失败“是否登录成功”请使用false
					OpenAPI.loginFeedBack(this, false,
							resultCode != null ? Integer.valueOf(resultCode)
									: -1, token);
				}
			} else {
				// sessionId验证返回的状态码没有请使用-1代替
				OpenAPI.loginFeedBack(this, true, -1, token);
			}

			if (!StringUtils.isEmpty(token)) {
				ALog.d("token: " + token + " \n");
			}

		} else {
			
		}
		ToastManager.getInstance().showText(this, R.string.msg_login_error);
	}

	@Override
	public void eCardCallBack(int arg0, String arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void eKeyCallBack(int arg0, String arg1, String arg2, String arg3) {
		// TODO Auto-generated method stub

	}

	private String oriSessionId;
	private FastLoginCallBack callback = new FastLoginCallBack() {

		@Override
		public void callBack(int code, String message, String uuid,
				String sessionId) {
			// TODO Auto-generated method stub

			LoadingProgressDialog.dismiss();

			LoadingProgressDialog.show(BookStoreActivity.this,
					R.string.msg_loading);

			// sessionId由sdk回调返回
			if (StringUtils.checkCallBackStat(code, sessionId)) {
				int i = 0;
				// 设置重试机制（避免服务超时造成的失败，仅供接入方参考）
				do {
					// 通过应用自身服务端与woa服务端进行sessionId验证（此步骤是判断登录成功与否的关键）
					String result = HttpUtil.readStringFromUrl("20008",
							sessionId, "utf-8", new Object());

					if (!StringUtils.isEmpty(result)) {
						if (StringUtils.checkHpsTimeOut(result)) {
							i++;
							continue;
						} else {
							LoadingProgressDialog.dismiss();
							CookieManager.getInstance().removeAllCookie();
							BookStoreActivity.user = StringUtils.getValueByKey(
									result, "sid");
							MobclickAgent.onEvent(BookStoreActivity.this, "bookstore","user:"+BookStoreActivity.user);
							PreferencesManager.getInstance().setSid(user);
							token = StringUtils.getValueByKey(result, "token");
							resultCode = StringUtils.getValueByKey(result,
									"Result");
							if (!StringUtils.isEmpty(token)
									&& "0".equals(resultCode)) {
								mWebView.loadUrl(WebUtil.getSid(mWebView.getUrl()));
								// 验证完sessionId后不管成功与否，都需要反馈给sdk
								// 调用反馈接口（接口参数：应用上下文，是否登录成功，sessionId验证返回的结果码，验证获取的token）
								// sessionId验证成功即可认为是此次登录成功
								OpenAPI.loginFeedBack(BookStoreActivity.this,
										true, resultCode != null ? Integer
												.valueOf(resultCode) : -1,
										token);
							} else {
								// sessionId验证失败“是否登录成功”请使用false
								OpenAPI.loginFeedBack(BookStoreActivity.this,
										false, resultCode != null ? Integer
												.valueOf(resultCode) : -1,
										token);
							}
							return ;
						}
					} else {
						// sessionId验证返回的状态码没有请使用-1代替
						OpenAPI.loginFeedBack(BookStoreActivity.this, false,
								-1, token);
					}
					break;
				} while (i < 3);

				if (!StringUtils.isEmpty(token)) {
				}

			} else {
				// sdk逻辑处理出现异常
				ALog.e("sdk逻辑处理出现异常");
			}
			LoadingProgressDialog.dismiss();
			ToastManager.getInstance().showText(BookStoreActivity.this, R.string.msg_login_error);
		}
	};

	@Override
	public void verifyCodeCallBack(int arg0, String arg1, String arg2,
			String arg3) {
		// TODO Auto-generated method stub
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
		
		if(!slidingDrawer.isOpened()){
			return false;
		}else{
			slidingDrawer.close();
			return true;
		}
	}
}